package br.com.android.games.daedal;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.provider.ContactsContract;

public class Preferences extends PreferenceActivity implements
		OnSharedPreferenceChangeListener {

	/**
	 * map com as preferencias que terá um tratamento no resumo
	 */
	private Map<Preference, Integer> summary_prefs = new HashMap<Preference, Integer>();
	private Map<String, String> summary_scrn = new HashMap<String, String>();

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.preference.PreferenceActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		/**
		 * Load interface
		 */
		addPreferencesFromResource(R.xml.preferences);

		/**
		 * Inicializar os atributos que tem o resumo atualizado com o valor
		 */
		summary_prefs.put(findPreference("aiPlayer"), R.string.pref_level_tip);
		summary_prefs.put(findPreference("nickname"), R.string.pref_your_name_tip);
		summary_prefs.put(findPreference("pname"),    R.string.pref_your_name_tip);

		/**
		 * Tratar o resume de telas internas
		 */
		summary_scrn.put("pname", "nickname");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		super.onPause();
		// Unregister the listener whenever a key changes
		getPreferenceScreen().getSharedPreferences()
				.unregisterOnSharedPreferenceChangeListener(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		super.onResume();

		SharedPreferences shared = getPreferenceScreen().getSharedPreferences();

		for (Preference pref : summary_prefs.keySet()) {
			String value_key = summary_scrn.get(pref.getKey());

			if (null == value_key)
				value_key = pref.getKey();

			String value = shared.getString(value_key, " ");
			pref.setSummary(getString(summary_prefs.get(pref), value));
		}

		findPreference("nickname").setEnabled(
				!shared.getBoolean("from_phone_book", false));
		shared.registerOnSharedPreferenceChangeListener(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.SharedPreferences.OnSharedPreferenceChangeListener#
	 * onSharedPreferenceChanged(android.content.SharedPreferences,
	 * java.lang.String)
	 */
	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {

		if (key.equals("from_phone_book")) {
			Boolean value = sharedPreferences.getBoolean(key, false);
			if (value) {
				Intent intent = new Intent(Intent.ACTION_PICK,
						ContactsContract.Contacts.CONTENT_URI);
				startActivityForResult(intent, 25);
			} else
				findPreference("nickname").setEnabled(!value);
		} else {
			Preference pKey = findPreference(key);
			Integer tip = summary_prefs.get(pKey);

			if (null != tip) {
				pKey.setSummary(getString(tip,
						sharedPreferences.getString(pKey.getKey(), " ")));
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.preference.PreferenceActivity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	public void onActivityResult(int reqCode, int resultCode, Intent data) {
		if (reqCode == 25) {
			SharedPreferences prefs = getPreferenceScreen()
					.getSharedPreferences();

			if (resultCode == Activity.RESULT_OK) {
				Uri contactData = data.getData();
				Cursor c = managedQuery(contactData, null, null, null, null);
				if (c.moveToFirst()) {

					String name = c
							.getString(c
									.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
					String key = c
							.getString(c
									.getColumnIndexOrThrow(ContactsContract.Contacts.LOOKUP_KEY));

					SharedPreferences.Editor editor = prefs.edit();

					editor.putString("nickname", name);
					editor.putString("lookupkey", key);
					editor.commit();
					findPreference("nickname").setEnabled(false);
				}
			} else {
				Editor editor = prefs.edit();
				editor.putBoolean("from_phone_book", false);
				editor.commit();
				finish();
				startActivity(getIntent());
			}
		}
	}
}
